import uuid
import datetime

from libs.tengxunyun.sms import MySmsSender
from django.shortcuts import HttpResponse, render, redirect
from web.myform.account import RegisterModelForm,SendSmsForm,LoginSmsForm,LoginForm
from django.conf import settings
from django.http import JsonResponse
from django.urls import reverse
from web.utils.img_code import image_code
from web import models


from django.db.models import Q
import redis
from django_redis import get_redis_connection
# 注册功能
def register(request):
	if request.method == 'GET':
		form = RegisterModelForm()
		return render(request,'register.html',{'form': form })
	# todo 校验注册数据
	else:
		form = RegisterModelForm(data=request.POST)
		if form.is_valid():
			instance = form.save()# instance就是当前记录对象
			# 注册成功之后,直接给用户一个免费版的策略

			price_policy_obj = models.PricePolicy.objects.filter(catogory=1,title='免费版').first()
			# 创建交易记录
			models.Transaction.objects.create(
				status=2,
				order=uuid.uuid4(),
				# 当前时间戳 + userid + ip地址等等 做唯一订单号
				user=instance,
				price_policy=price_policy_obj,
				count = 0,
				price=0,
				start_datetime=datetime.datetime.now(),
			)

			return JsonResponse({'status':True,'path':reverse('login_sms')})
		else:
			return JsonResponse({'status':False,'error_msg':form.errors})





#获取手机号,校验手机号,发送短信验证码
def sms_code(request):
	# 校验手机号,格式,手机号唯一性验证

	print("phone",request.GET.get('phone'))
	print("tpl",request.GET.get('tpl'))
	print("get",request.GET)

	form = SendSmsForm(request,data=request.GET)
	if form.is_valid():



		return JsonResponse({'status':True})
	else:
		return JsonResponse({'status':False,'error_msg':form.errors})

# 短信验证码登录
def login_sms(request):
	if request.method == 'GET':
		form = LoginSmsForm()
		return render(request, 'login_sms.html',{'form':form})

	else:
		form = LoginSmsForm(data=request.POST)
		if form.is_valid():
			phone = form.cleaned_data.get('phone')

			user_obj = models.UserInfo.objects.filter(phone=phone).first()
			# todo 将登录成功之后的数据保存到session中,以便以后使用
			request.session['user_id'] = user_obj.id
			request.session.set_expiry(60*60*24*14)

			return JsonResponse({'status':True,'path':reverse('index')})

		else:
			return JsonResponse({'status':False,'error_msg':form.errors})


def index(request):
	return render(request,'index.html')

def login(request):

	if request.method == 'GET':
		form = LoginForm(request)
		return render(request,'login.html',{'form':form})

	else:
		form = LoginForm(request,data=request.POST)
		if form.is_valid():
			# todo 将登录成功之后的数据保存到session,以便后续使用
			uname = form.cleaned_data.get('username')

			user_obj = models.UserInfo.objects.filter(Q(phone=uname)|Q(email=uname)).first()

			request.session['user_id'] = user_obj.id
			request.session.set_expiry(60 * 60 * 24 * 14)

			return JsonResponse({'status':True, 'path' : reverse('index')})

		else:
			return JsonResponse({'status':False , 'error_msg':form.errors})


def img_code(request):
	img, char_code = image_code()

	# 将图片数据保存到本地文件中
	#with open('code.png','wb') as f:
	#	img.save(f,format='png')

	#with open('code.png', 'rb') as f:
	#	data = f.read()

	# 将图片数据写到内存
	from io import BytesIO
	stream = BytesIO()
	img.save(stream, format='png')
	# 内存中获取图片数据 stream.getvalue , 结果为bytes数据
	# request.session.flush() 清除session数据
	# 将图片验证码保存到session中
	request.session['image_code'] = char_code
	# 图片验证码有效期,单位秒
	request.session.set_expiry(settings.IMAGE_CODE_EXPIRE)

	return HttpResponse(stream.getvalue())



def logout(request):
	request.session.flush()
	return redirect('login')


